import React from 'react';
import Router from 'next/router';
import { Alert } from 'antd';
import 'isomorphic-fetch';
import styled from 'styled-components';
import withCtx from '/app/withCtx';
import { withReduxSaga } from '/app/reudx/store';
import LoginForm from '/app/components/userAuth/LoginForm.js';
// import Logo from '../../static/icon/main_logo.svg';

const LoginWrap = styled.div`
	width: 100%;
	padding-top: 140px;
`
const Header = styled.div`
	text-align: center;
	margin-bottom: 50px;
`
const Title = styled.h1` 
	font-weight: 1000;
`
const Main = styled.div`
	width: 368px;
	margin: 0 auto;
`
class Login extends React.Component {
	static async getInitialProps(ctx) {
    // console.log('ctx:', ctx);
    return {};
  }
  constructor(props) {
    super(props);
    this.state = {
    	loginSucc: null,
    	loginTips: '',
    };
  }
  handleLogin = params => {
  	const api = 'http://localhost:3000/v1/login';
  	const body = JSON.stringify({
  		username: params.username,
  		password: params.password,
  	});
  	fetch(api, {
  		method: 'POST',
  		credentials: 'include',
  		headers: {
  			'Accept': 'application/json',
  			'Content-Type': 'application/json'
  		},
  		body,
  	}).then((response) => {
  		return response.json(); 
  	}).then((res) => {
  		if (res.code === 0) {
  			const role = res.data.role;
        
        this.setState({
  				loginSucc: true
  			});
        
        switch (role) {
          case 1: Router.replace('/student');break;
          case 2: Router.replace('/teacher');break;
          case 3: Router.replace('/manager');break;
          default: Router.replace('/');
        }
  		} else {
  			this.setState({
  				loginSucc: false,
  				loginTips: '账户或密码错误',
  			});
  		}
  	}).catch((err) => {
  		console.log(err);
  		this.setState({
  			loginTips: err,
  			loginSucc: false,
  		});
  	})
  }
	render() {
		const { loginSucc, loginTips } = this.state;
		return (
			<LoginWrap>
				<Header>
				  <Title><img src="../../static/icon/main_logo.svg" />&nbsp;&nbsp;前端个性化学习系统</Title>
					<p>为学生量身订造的前端知识学习平台</p>	
				</Header>
				<Main>
					<Alert
			      message={loginTips}
			      type="error"
			      showIcon
			      style={{
			      	display: loginSucc === false ? 'block': 'none'
			      }}
			    />
			    <br />
					<LoginForm handleLogin={this.handleLogin} />
				</Main>
			</LoginWrap>
		)
	}
}

function select (store) {
	return {
		userAuth: store.userAuth,
	};
}

export default withReduxSaga(withCtx(Login), select);